<?php

/**
 * user actions.
 *
 * @package    dylemat
 * @subpackage user
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions {

    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request) {
        //TODO  kurwa poprawic! ostatni wolny
        $this->signin = ActivPlayerPeer::retrieveByUserAndStatuN($this->getUser()->getUserId(), ActivPlayer::$ACTION_END_TURNAMENT);
        //$this->mt=$this->getUser()->getActualMatch();
        /*
          $mt=new gameRulesMatrix("MatrixRulez","Oskarzony1","Oskarzony2",array("Przyznaj","Milcz"),array("Przyznaj","Milcz"),array(array(10,10),array(2,4),array(4,2),array(0,0)),gameRules::$EM_GAME,12);

          $rul=new Rules();
          $rul->setName($mt->getName());
          $rul->setData(serialize($mt));
          $rul->setType($mt->getType());
          $rul->save();
         */
        /* if($v=$this->getUser()->getActualMatch())
          {

          }else{
         */
        /* $mh=new Match();
          $mh->setFirstPlayerId($this->getUser()->getUserId());
          $mh->setTurnamentId(1);
          $mh->save();
         */
        //	}
    }

    public function executeUserProfile(sfWebRequest $request) {

        $this->user_id = $this->getUser()->getPlayer()->getId();

        $c = new Criteria();
        $c->addSelectColumn(TournamentPeer::ID);
        $c->addSelectColumn(TournamentPeer::NAME);
        $c->addSelectColumn(TournamentPeer::STATUS);
        $c->addSelectColumn(ActivPlayerPeer::CREATED_AT);
        $c->addSelectColumn(ActivPlayerPeer::ID);
        $c->addJoin(ActivPlayerPeer::TOURNAMENT_ID, TournamentPeer::ID);
        $c->add(ActivPlayerPeer::USER_ID, $this->user_id);
        $c->addDescendingOrderByColumn(ActivPlayerPeer::CREATED_AT);
        $activTournaments = ScorePeer::doSelectStmt($c);

        $this->tournaments = array();
        $this->tour_ids = array();
        $this->activ_ids = array();

        foreach ($activTournaments->fetchAll() as $t) {
            $this->tournaments[] = array($t[0], $t[1], $t[2], $t[3]);
            $this->tour_ids[] = $t[0];
            $this->activ_ids[] = $t[4];
        }

        $this->wins = 0;
        $this->loses = 0;
        $this->draws = 0;

        //pobieranie danych meczów
        $c = new Criteria();
        $c->addSelectColumn(GameMatchPeer::ID);
        $c->addSelectColumn(GameMatchPeer::ROUND_ID);
        $c->addSelectColumn(GameMatchPeer::FIRST_PLAYER_ID);
        $c->addSelectColumn(GameMatchPeer::SECOND_PLAYER_ID);
        $c->addSelectColumn(GameMatchPeer::RESULT);
        $c->add(GameMatchPeer::TOURNAMENT_ID, $this->tour_ids, Criteria::IN);
        $c->add(GameMatchPeer::STATUS, GameMatch::$GAMEMATCH_STATUS_ENDED);
        $crit1 = $c->getNewCriterion(GameMatchPeer::FIRST_PLAYER_ID, $this->activ_ids, Criteria::IN);
        $crit2 = $c->getNewCriterion(GameMatchPeer::SECOND_PLAYER_ID, $this->activ_ids, Criteria::IN);
        $c->add($crit1);
        $crit1->addOr($crit2);
        $c->add($crit1);
        $this->matches = GameMatchPeer::doSelectStmt($c);

        $match_ids = array();
        $this->aMatches = array();
        foreach ($this->matches->fetchAll() as $m) {
            $match_ids[] = $m[0];
            $this->aMatches[$m[0]] = array($m[1], $m[2], $m[3], $m[4]); // id | round activfirst activsecond result
        }

        foreach ($this->matches->fetchAll() as $m) {
            
        }

        foreach ($this->aMatches as $key => $value) {
            switch ($this->aMatches[$key][3]) {
                case GameMatch::$GAMEMATCH_RESULT_DRAW:
                    $this->draws++;
                    break;
                case GameMatch::$GAMEMATCH_RESULT_FIRST:
                    if (in_array($this->aMatches[$key][1], $this->activ_ids)) {
                        $this->wins++;
                    } else {
                        $this->loses++;
                    }
                    break;
                case GameMatch::$GAMEMATCH_RESULT_SECOND:
                    if ($this->aMatches[$key][2] == $this->active_id) {
                        $this->wins++;
                    } else {
                        $this->loses++;
                    }
                    break;
            }
        }
    }

    public function executeChangePassword(sfWebRequest $request) {
        $this->form = new PasswordForm();
        if ($request->isMethod('post')) {
            $this->form->bind($request->getParameter('password'));
            if ($this->form->isValid()) {
                //$this->form->save();

                if ($this->getUser()->checkPassword($this->form->getValue('oldpassword')) && ($this->form->getValue('newpassword1') === $this->form->getValue('newpassword2'))) {
                    $this->getUser()->getGuardUser()->setPassword($this->form->getValue('newpassword1'));
                    $this->getUser()->getGuardUser()->save();
                    $this->getUser()->setFlash('notice', 'Hasło zostało zmienione.');
                    $this->redirect('@user_profile');
                } else {
                    $this->getUser()->setFlash('error', 'Stare hasło nie zgadza się lub niepoprawnie powtórzono nowe hasło.');
                    $this->redirect('@change_password');
                }
            }
        }
        //$this->redirect('@user_profile');
    }

    public function executeHelp(sfWebRequest $request) {
        
    }

    public function executeUserHistory(sfWebRequest $request) {
        $c = new Criteria();
        $c->add(TournamentPeer::ID, $request->getParameter('id'));
        $this->tour = TournamentPeer::doSelectOne($c);
        $this->error = null;

        if ($this->tour) {
            $this->tour_id = $this->tour->getId();
            $this->user_id = $this->getUser()->getPlayer()->getId();

            $c = new Criteria();
            $c->add(ActivPlayerPeer::TOURNAMENT_ID, $this->tour->getId());
            $c->add(ActivPlayerPeer::USER_ID, $this->user_id);
            $this->active = ActivPlayerPeer::doSelectOne($c);


            if ($this->active) {

                $this->active_id = $this->active->getId();

                if (!$this->matches) {
                    $this->rules = $this->tour->getRules();
                    $this->ruleData = unserialize($this->rules->getData());

                    $this->wins = 0;
                    $this->loses = 0;
                    $this->draws = 0;




                    //ranking
                    
                    $c = new Criteria();
                    $c->add(GameMatchPeer::TOURNAMENT_ID, $this->tour_id);
                    $c->add(GameMatchPeer::STATUS,GameMatch::$GAMEMATCH_STATUS_ENDED);
                    $result = GameMatchPeer::doSelect($c);

                    $all_match = array();

                    foreach ($result as $res) {
                        $all_match[] = $res->getId();
                    }
                    
                    $c = new Criteria();
                    $c->addSelectColumn(ScorePeer::PLAYER_ID);
                    $c->addSelectColumn('SUM(' . ScorePeer::SCORE . ') as cnt');
                    $c->add(ScorePeer::MATCH_ID, $all_match, Criteria::IN);
                    $c->addGroupByColumn(ScorePeer::PLAYER_ID);

                    $mt = unserialize($this->tour->getRules()->getData());

                    if ($mt->getWinPoints() == gameRules::$GW_Less)
                        $c->addAscendingOrderByColumn('cnt');
                    else
                        $c->addDescendingOrderByColumn('cnt');

                    $res = ScorePeer::doSelectStmt($c);

                    //cd nizej

                    //pobieranie danych meczu
                    $c = new Criteria();
                    $c->addSelectColumn(GameMatchPeer::ID);
                    $c->addSelectColumn(GameMatchPeer::ROUND_ID);
                    $c->addSelectColumn(GameMatchPeer::FIRST_PLAYER_ID);
                    $c->addSelectColumn(GameMatchPeer::SECOND_PLAYER_ID);
                    $c->addSelectColumn(GameMatchPeer::RESULT);
                    $c->add(GameMatchPeer::TOURNAMENT_ID, $this->tour_id);
                    $c->add(GameMatchPeer::STATUS, GameMatch::$GAMEMATCH_STATUS_ENDED);
                    $crit1 = $c->getNewCriterion(GameMatchPeer::FIRST_PLAYER_ID, $this->active_id);
                    $crit2 = $c->getNewCriterion(GameMatchPeer::SECOND_PLAYER_ID, $this->active_id);
                    $c->add($crit1);
                    $crit1->addOr($crit2);
                    $c->add($crit1);
                    $this->matches = GameMatchPeer::doSelectStmt($c);

                    $match_ids = array();
                    $this->aMatches = array();
                    foreach ($this->matches->fetchAll() as $m) {
                        $match_ids[] = $m[0];
                        $this->aMatches[$m[0]] = array($m[1], $m[2], $m[3], $m[4], '', '', 0, 0); // id | round activfirst activsecond result | nick1 nick2 score1 score2
                    }

                    foreach ($this->matches->fetchAll() as $m) {
                        
                    }

                    //pobieranie nicków activ_playerów
                    $c = new Criteria();
                    $c->addSelectColumn(ActivPlayerPeer::ID);
                    $c->addSelectColumn(PlayerPeer::NICK);
                    $c->addJoin(ActivPlayerPeer::USER_ID, PlayerPeer::ID);
                    $c->add(ActivPlayerPeer::TOURNAMENT_ID, $this->tour_id);
                    $c->addAscendingOrderByColumn(ActivPlayerPeer::ID);
                    $this->nicks = ScorePeer::doSelectStmt($c);

                    //pobieranie sumy punktów
                    $c = new Criteria();
                    $c->addSelectColumn(ScorePeer::MATCH_ID);
                    $c->addSelectColumn(ScorePeer::PLAYER_ID);
                    $c->addSelectColumn('SUM(' . ScorePeer::SCORE . ') as sum');
                    $c->add(ScorePeer::MATCH_ID, $match_ids, Criteria::IN);
                    $c->addGroupByColumn(ScorePeer::MATCH_ID);
                    $c->addGroupByColumn(ScorePeer::PLAYER_ID);
                    $c->addAscendingOrderByColumn(ScorePeer::MATCH_ID);
                    $c->addAscendingOrderByColumn(ScorePeer::PLAYER_ID);
                    $this->scores = ScorePeer::doSelectStmt($c);

                    $this->aScores = array();
                    foreach ($this->scores->fetchAll() as $s) {
                        $this->aScores[] = array($s[0], $s[1], $s[2]); //match player sum
                    }

                    $this->aNicks = array();
                    foreach ($this->nicks->fetchAll() as $n) {
                        $this->aNicks[$n[0]] = $n[1]; //index to activ id a value to nick
                    }

                    //ranking
                    
                    $this->ranking = array();

                    foreach ($res->fetchAll() as $node) {
                        $this->ranking[] = array($this->aNicks[$node[0]],$node[1]);                        
                    }
                    
                    ///ranking
                    foreach ($this->aMatches as $key => $value) {
                        $this->aMatches[$key][4] = $this->aNicks[$value[1]];
                        $this->aMatches[$key][5] = $this->aNicks[$value[2]];

                        foreach ($this->aScores as $s) {
                            if ($key == $s[0] && $value[1] == $s[1]) {
                                $this->aMatches[$key][6] = $s[2];
                            }
                            if ($key == $s[0] && $value[2] == $s[1]) {
                                $this->aMatches[$key][7] = $s[2];
                            }
                        }

                        switch ($this->aMatches[$key][3]) {
                            case GameMatch::$GAMEMATCH_RESULT_DRAW:
                                $this->aMatches[$key][3] = "remis";
                                $this->draws++;
                                break;
                            case GameMatch::$GAMEMATCH_RESULT_FIRST:
                                if ($this->aMatches[$key][1] == $this->active_id) {
                                    $this->aMatches[$key][3] = "wygrany";
                                    $this->wins++;
                                } else {
                                    $this->aMatches[$key][3] = "przegrany";
                                    $this->loses++;
                                }
                                break;
                            case GameMatch::$GAMEMATCH_RESULT_SECOND:
                                if ($this->aMatches[$key][2] == $this->active_id) {
                                    $this->aMatches[$key][3] = "wygrany";
                                    $this->wins++;
                                } else {
                                    $this->aMatches[$key][3] = "przegrany";
                                    $this->loses++;
                                }
                                break;
                        }
                    }
                } else {
                    $this->error = "Brak danych historycznych.";
                    return;
                }
            } else {
                $this->error = "Gracz nie brał udziału w tym turnieju.";
                return;
            }
        } else {
            $this->error = "Turniej nie istnieje.";
            return;
        }
    }

}
